package com.tanhua.sso.service;

import com.aliyun.oss.OSSClient;
import com.tanhua.sso.config.AliyunOSSConfig;
import com.tanhua.sso.vo.PicUploadResult;
import org.apache.commons.lang3.RandomUtils;
import org.apache.commons.lang3.StringUtils;
import org.joda.time.DateTime;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;

import java.io.ByteArrayInputStream;
import java.io.IOException;

/**
 * 文件上传服务
 */
@Service
public class PicUploadService {

    @Autowired
    private OSSClient ossClient;
    @Autowired
    private AliyunOSSConfig aliyunOSSConfig;

    // 允许上传的格式
    private static final String[] IMAGE_TYPE = new String[]{".bmp", ".jpg", ".jpeg", ".gif", ".png"};

    public PicUploadResult upload(MultipartFile uploadFile) throws IOException {
        PicUploadResult result = new PicUploadResult();

        //图片做校验，对后缀名
        if (!StringUtils.endsWithAny(uploadFile.getOriginalFilename(), IMAGE_TYPE)) {
            result.setStatus("error");
            return result;
        }

        // 文件新路径
        String fileName = uploadFile.getOriginalFilename();
        String filePath = getFilePath(fileName);
        // 上传到阿里云，目录结构：images/2018/12/29/xxxx.jpg
        ossClient.putObject(aliyunOSSConfig.getBucketName(), filePath, new ByteArrayInputStream(uploadFile.getBytes()));
        // 上传成功
        result.setStatus("done");
        result.setName(this.aliyunOSSConfig.getUrlPrefix() + filePath);
        result.setUid(String.valueOf(System.currentTimeMillis()));
        return result;
    }

    private String getFilePath(String sourceFileName) {
        DateTime dateTime = new DateTime();
        return "images/" + dateTime.toString("yyyy") + "/" + dateTime.toString("MM") + "/" + dateTime.toString("dd") + "/" + System.currentTimeMillis() + RandomUtils.nextInt(100, 9999) + "." + StringUtils.substringAfterLast(sourceFileName, ".");
    }

}
